package com.hucheng.pay.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.hucheng.common.exception.EduException;
import com.hucheng.common.utils.AlipayUtils;
import com.hucheng.order.service.OrderService;
import com.hucheng.pay.config.AliPaySystem;
import com.hucheng.pay.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-07-17
 * @Description: 支付宝支付实现类
 **/
@Slf4j
@Component
@Service(interfaceClass = AlipayService.class, retries = -1, timeout = 5000)
public class AlipayServiceImpl implements AlipayService {

    @Reference
    private OrderService orderService;

    @Autowired
    private AliPaySystem aliPaySystem;

    /**
     * 支付宝网页支付
     *
     * @param orderId 订单id
     * @throws AlipayApiException
     */
    @Override
    public String alipayTradePagePay(Integer userId, String orderId, String orderNumber, String payAmount) throws AlipayApiException, UnsupportedEncodingException {

        AlipayClient alipayClient = AlipayUtils.getAlipayClient(aliPaySystem.getAliPay());
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        alipayRequest.setReturnUrl(AlipayUtils.getReturnUrl(aliPaySystem.getAliPay()));
        alipayRequest.setNotifyUrl(AlipayUtils.getNotifyUrl(aliPaySystem.getAliPay()));

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderNumber.getBytes("ISO-8859-1"), "utf-8");
        String total_amount = new String(payAmount.getBytes("ISO-8859-1"), "utf-8");
        String subject = new String(("TT" + orderNumber).getBytes("ISO-8859-1"), "utf-8");
        String body = new String(("TT" + orderNumber).getBytes("ISO-8859-1"), "utf-8");

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        bizContent.put("body", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        alipayRequest.setBizContent(bizContent.toJSONString());

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }

    @Override
    public void updateOrderStatus(Map<String, String> params) throws AlipayApiException, EduException {
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPaySystem.getAliPay().get("alipay_public_key"),
                aliPaySystem.getAliPay().get("charset"),
                aliPaySystem.getAliPay().get("sign_type"));
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            log.info("支付宝回调参数 >>>>>>>>> " + params);
            //修改订单状态
            orderService.updateOrderStatus(params);
            //商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //支付宝交易号
//            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //付款金额
//            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
//
//            out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
        } else {
            throw new EduException(110009);
        }
    }

    @Override
    public String precreate(Integer userId, String orderId, String orderNumber, String payAmount) throws AlipayApiException, UnsupportedEncodingException {

        AlipayClient alipayClient = AlipayUtils.getAlipayClient(aliPaySystem.getAliPay());
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        request.setReturnUrl(AlipayUtils.getReturnUrl(aliPaySystem.getAliPay()));
        request.setNotifyUrl(AlipayUtils.getNotifyUrl(aliPaySystem.getAliPay()));

        String out_trade_no = new String(orderNumber.getBytes("ISO-8859-1"), "utf-8");
        String total_amount = new String(payAmount.getBytes("ISO-8859-1"), "utf-8");
        String subject = new String(("QR" + orderNumber).getBytes("ISO-8859-1"), "utf-8");
        String store_id = new String("NJ_001".getBytes("ISO-8859-1"), "utf-8");

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        bizContent.put("store_id", store_id);

        request.setBizContent(bizContent.toJSONString());

        //通过alipayClient调用API，获得对应的response类
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        JSONObject qrInfo = jsonObject.getJSONObject("alipay_trade_precreate_response");
        System.out.print(qrInfo.getString("qr_code"));
        String result = qrInfo.getString("qr_code");
        return result;
    }
}
